<template>
  <div class="comment-list-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>评论管理</h2>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-filter">
      <el-input
          v-model="searchKeyword"
          placeholder="请输入评论内容搜索"
          clearable
          prefix-icon="search"
          class="search-input"
      ></el-input>

      <el-select
          v-model="selectedStatus"
          placeholder="选择评论状态"
          clearable
          class="status-select"
      >
        <el-option label="全部" value=""></el-option>
        <el-option label="已通过" value="approved"></el-option>
        <el-option label="待审核" value="pending"></el-option>
        <el-option label="已拒绝" value="rejected"></el-option>
      </el-select>

      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetFilter">重置</el-button>
    </div>

    <!-- 评论列表表格 -->
    <el-table
        :data="commentList"
        border
        stripe
        style="width: 100%; margin-top: 16px;"
        v-loading="loading"
    >
      <el-table-column
          type="index"
          label="序号"
          width="80"
          align="center"
      ></el-table-column>

      <el-table-column
          prop="content"
          label="评论内容"
          min-width="300"
      ></el-table-column>

      <el-table-column
          prop="articleTitle"
          label="所属文章"
          min-width="200"
      >
        <template #default="scope">
          <a :href="`/news/articles/${scope.row.articleId}`" class="article-link">{{ scope.row.articleTitle }}</a>
        </template>
      </el-table-column>

      <el-table-column
          prop="username"
          label="评论用户"
          width="120"
          align="center"
      ></el-table-column>

      <el-table-column
          prop="createTime"
          label="评论时间"
          width="180"
          align="center"
          :formatter="formatDate"
      ></el-table-column>

      <el-table-column
          prop="status"
          label="状态"
          width="120"
          align="center"
      >
        <template #default="scope">
          <el-tag
              :type="getStatusTagType(scope.row.status)"
          >
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
          label="操作"
          width="220"
          align="center"
      >
        <template #default="scope">
          <el-button
              size="small"
              type="text"
              @click="handleReply(scope.row)"
              v-if="scope.row.status === 'approved'"
          >
            回复
          </el-button>
          <el-button
              size="small"
              type="success"
              @click="handleApprove(scope.row)"
              v-if="scope.row.status === 'pending'"
          >
            通过
          </el-button>
          <el-button
              size="small"
              type="danger"
              @click="handleReject(scope.row)"
              v-if="scope.row.status === 'pending'"
          >
            拒绝
          </el-button>
          <el-button
              size="small"
              type="warning"
              @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>
    </div>

    <!-- 回复评论对话框 -->
    <el-dialog
        title="回复评论"
        v-model="replyDialogVisible"
        width="500px"
    >
      <el-input
          type="textarea"
          v-model="replyContent"
          placeholder="请输入回复内容"
          rows="5"
      ></el-input>
      <template #footer>
        <el-button @click="replyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitReply">提交回复</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, toRefs } from 'vue';
import { ElMessage } from 'element-plus';
import { getCommentList, updateCommentStatus, deleteComment, replyToComment } from '@/api/news';

// 状态管理
const state = reactive({
  commentList: [],
  searchKeyword: '',
  selectedStatus: '',
  currentPage: 1,
  pageSize: 10,
  total: 0,
  loading: false,
  replyDialogVisible: false,
  replyContent: '',
  currentComment: null
});

const {
  commentList,
  searchKeyword,
  selectedStatus,
  currentPage,
  pageSize,
  total,
  loading,
  replyDialogVisible,
  replyContent,
  currentComment
} = toRefs(state);

// 生命周期钩子 - 页面加载时获取数据
onMounted(() => {
  fetchCommentList();
});

// 获取评论列表数据
const fetchCommentList = async () => {
  state.loading = true;
  try {
    const params = {
      keyword: state.searchKeyword,
      status: state.selectedStatus,
      page: state.currentPage,
      size: state.pageSize
    };

    const response = await getCommentList(params);
    state.commentList = response.data.records;
    state.total = response.data.total;
  } catch (error) {
    ElMessage.error('获取评论列表失败: ' + (error.message || '未知错误'));
  } finally {
    state.loading = false;
  }
};

// 搜索评论
const handleSearch = () => {
  state.currentPage = 1; // 重置为第一页
  fetchCommentList();
};

// 重置筛选条件
const resetFilter = () => {
  state.searchKeyword = '';
  state.selectedStatus = '';
  state.currentPage = 1;
  fetchCommentList();
};

// 分页大小变化
const handleSizeChange = (size) => {
  state.pageSize = size;
  fetchCommentList();
};

// 当前页变化
const handleCurrentChange = (page) => {
  state.currentPage = page;
  fetchCommentList();
};

// 格式化日期
const formatDate = (row, column, cellValue) => {
  if (!cellValue) return '';
  const date = new Date(cellValue);
  return date.toLocaleString();
};

// 获取状态显示文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待审核',
    'approved': '已通过',
    'rejected': '已拒绝'
  };
  return statusMap[status] || status;
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    'pending': 'warning',
    'approved': 'success',
    'rejected': 'danger'
  };
  return typeMap[status] || 'info';
};

// 回复评论
const handleReply = (comment) => {
  state.currentComment = comment;
  state.replyContent = '';
  state.replyDialogVisible = true;
};

// 提交回复
const handleSubmitReply = async () => {
  if (!state.replyContent.trim()) {
    ElMessage.warning('回复内容不能为空');
    return;
  }

  try {
    await replyToComment({
      commentId: state.currentComment.id,
      content: state.replyContent
    });
    ElMessage.success('回复成功');
    state.replyDialogVisible = false;
    fetchCommentList(); // 重新加载列表
  } catch (error) {
    ElMessage.error('回复失败: ' + (error.message || '未知错误'));
  }
};

// 审核通过
const handleApprove = async (comment) => {
  try {
    await updateCommentStatus(comment.id, 'approved');
    ElMessage.success('审核通过');
    fetchCommentList(); // 重新加载列表
  } catch (error) {
    ElMessage.error('操作失败: ' + (error.message || '未知错误'));
  }
};

// 审核拒绝
const handleReject = async (comment) => {
  try {
    await updateCommentStatus(comment.id, 'rejected');
    ElMessage.success('已拒绝');
    fetchCommentList(); // 重新加载列表
  } catch (error) {
    ElMessage.error('操作失败: ' + (error.message || '未知错误'));
  }
};

// 删除评论
const handleDelete = async (comment) => {
  try {
    await deleteComment(comment.id);
    ElMessage.success('删除成功');
    fetchCommentList(); // 重新加载列表
  } catch (error) {
    ElMessage.error('删除失败: ' + (error.message || '未知错误'));
  }
};
</script>

<style scoped>
.comment-list-container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 120px);
}

.page-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.search-filter {
  display: flex;
  gap: 12px;
  align-items: center;
  margin-bottom: 16px;
}

.search-input {
  width: 300px;
}

.status-select {
  width: 180px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.article-link {
  color: #409eff;
  text-decoration: none;
}

.article-link:hover {
  text-decoration: underline;
}
</style>
